import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { App } from "vue";
import { createRouterGuard } from "@/router/guard";
import { RoutePathEnum } from "@/enums/RouteEnum";

/**
 * @description 自动化引入(方法globEager已弃用).
 */
const modules: CustomerRoute.RouteModule = import.meta.glob(
  "./modules/**/*.ts",
  {
    eager: true,
  }
);

/**
 * 路由列表
 */
const routeModuleList: CustomerRoute.Route[] = [];

/**
 * 循环添加所有文件中的路由.
 */
Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

const baseRoutes: RouteRecordRaw[] = [
  {
    name: "sign-in",
    path: RoutePathEnum.BASE_LOGIN,
    component: () => import("@/views/sign-in/SignIn.vue"),
    meta: {
      title: "登录",
    },
  },
];

/**
 * 菜单排序
 */
function sortRoute(a: CustomerRoute.Route, b: CustomerRoute.Route) {
  return (a.meta?.sort || 0) - (b.meta?.sort || 0);
}

routeModuleList.sort(sortRoute);

/**
 * @description 定义路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: baseRoutes,
  strict: true,
});

export const constantRoutes = baseRoutes;

export const asyncRoutes = [...routeModuleList];

/**
 * @description 挂载路由
 */
export async function setupRouter(app: App) {
  app.use(router);

  /**
   * 创建路由守卫
   */
  createRouterGuard(router);

  /**
   * 路由准备就绪，挂载APP实例
   */
  await router.isReady();
}

export default router;
